package com.sczmgk.hotline.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.sczmgk.hotline.MainActivity;
import com.sczmgk.hotline.R;
import com.sczmgk.hotline.base.CheckPermissionBaseActivity;
import com.sczmgk.hotline.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline.constant.Constant;
import com.sczmgk.hotline.dialog.DialogFactory;
import com.sczmgk.hotline.dialog.MessageDialog;
import com.sczmgk.hotline.entity.VersionBean;
import com.sczmgk.hotline.httpUtils.MyHttp;
import com.sczmgk.hotline.utils.CommonUtils;
import com.sczmgk.hotline.utils.FileUtil;
import com.sczmgk.hotline.utils.IndicatorUtils;
import com.sczmgk.hotline.utils.MyLog;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

import static com.sczmgk.hotline.MyApp.imei;
import static com.sczmgk.hotline.utils.FileUtil.getAPKPath;

/**
 * Created by Administrator on 2017/12/5.
 */
public class SplashActivity extends CheckPermissionBaseActivity {

    private boolean isUpdata = false;
    private final String TAG = "SplashActivity";
    private ProgressDialog progressDialog;

    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setTheme(R.style.SplashTheme);

        MyLog.e(TAG,"SplashActivity  onCreate");
        setContentView(R.layout.activity_splash);
        goneHeadView();
        checkStroage(0, TYPE_NORMAL);
    }

    private void onStroagePermissionOk() {

        checkPhone("");

    }

    private void initData() {
        MyLog.i(TAG, "phone state permission ok!");
        imei = CommonUtils.getPhoneImei(getApplicationContext());
//        imei = "dsfdfdgdfgfdgfdhgfhtyr";

        startActivity();

//        //检查新版本
//        checkVersion();
        //获取文章指示器
        IndicatorUtils.getIndicator(SplashActivity.this);
    }

    /**
     * 获取版本信息并自动更新
     */
    private void checkVersion(){
        //1.获取App版本信息
        Map<String,Object> dataMaps = new HashMap<>();
        dataMaps.put("source",1);//1->Android 0->iOS
        dataMaps.put("channel",getMyChannel());
        dataMaps.put("softname",1);//0 -> 业务App   1 ->  乐政App
        MyHttp.request(SplashActivity.this, Constant.BASE_URL + Constant.GET_APP_VERSION, dataMaps, MyHttp.POST, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {

            }

            @Override
            public void onVerifySuccess(String dataRaw) {
                parseJson(dataRaw);
            }

            @Override
            public void onServerUnKnownError() {

            }

            @Override
            public void onErrorCodeError(String msg) {

            }
        });

    }


    private void parseJson(String dataRaw) {
        Gson gson = new Gson();
        final VersionBean versionBean = gson.fromJson(dataRaw, VersionBean.class);
        MyLog.d(TAG,"取得版本信息："+dataRaw);
        //2.判断是否有新版本
        int appVersionCode = CommonUtils.getAppVersionCode(getApplicationContext());
        MyLog.i(TAG,"手机app版本号："+appVersionCode);
        if(versionBean.softcode > appVersionCode){
            MyLog.d(TAG,"打开对话框");
            isUpdata = true;
            //3.提示对话框
            final MessageDialog messageDialog = DialogFactory.chooseDialog(SplashActivity.this, versionBean.remark, "是", "否", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //下载新版本
                    downloadApk(versionBean.downloadurl);
                }
            }, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }
            });
            messageDialog.setTitle("版本更新");
            messageDialog.show();
            //4.下载apk.
            //5.安装apk
        }
    }

    /**
     *
     * @return
     */
    private String getMyChannel() {
        //TODO 取得渠道
        String  channel = null;
        try {
            ApplicationInfo  appInfo = this.getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
            channel =appInfo.metaData.getString("UMENG_CHANNEL");
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
      return channel;
    }

    private void startActivity() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(isUpdata){
                    MyLog.d(TAG,"有更新，不跳转界面");
                }else{
                    MyLog.e(TAG,"没有更新进入登录页");
//                    final boolean isFirstIn = CacheUtils.getBooleanData(SplashActivity.this, Constant.IS_FIRST_IN, true);
//                    if (isFirstIn) {
//                        startActivity(new Intent(SplashActivity.this, GuideActivity.class));
//                    } else {
                        startActivity(new Intent(SplashActivity.this, MainActivity.class));
//                    }
                    finish();
                }
            }
        }, 3000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.init(this);            // 初始化 JPush
        JPushInterface.setDebugMode(false);    // 设置开启日志,发布时请关闭日志
        JPushInterface.onResume(getApplicationContext());
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(getApplicationContext());
    }

    @Override
    public void onSelectedPhonePermission(String phoneNumber) {
        initData();
    }

    @Override
    public void onSelectedStroage(int position) {
        MyLog.i(TAG, "stroage permission ok!");
        onStroagePermissionOk();
        FileUtil.initAppStoragePath(getApplicationContext());
    }

    @Override
    public void onSelectCamera(int position) {

    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }

    private void downloadApk(String url) {
        HttpUtils httpUtils  = new HttpUtils();
        String  filePath = getAPKPath();
        if(!FileUtil.isFile(filePath)){
            new File(filePath);
        }

        MyLog.i(TAG,"开始下载apk----- -->url:"+url+"  file path: "+ getAPKPath());


        httpUtils.download(url, getAPKPath(), new RequestCallBack<File>() {
            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {

                //下载完成提示安装
                installApk();
                MyLog.d(TAG,"apk 下载完成");

                if(progressDialog.isShowing()){
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }

            @Override
            public void onLoading(final long total, final long current, final boolean isUploading) {


                super.onLoading(total, current, isUploading);
                MyLog.d(TAG,"下载进度："+current);
                showProgress(total,current,isUploading);

            }
        });

    }


    /**
     * 安装apk
     */
    private void installApk() {

        File fileLocation = new File(getAPKPath());
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory("android.intent.category.DEFAULT");
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(fileLocation), "application/vnd.android.package-archive");
        this.startActivityForResult(intent,1);
        //停止服务
    }


    /**
     *展示进度条对话框
     * @param total
     * @param current
     * @param isUploading
     */
    private void showProgress(long total,long current,boolean isUploading){

        //下载进度
        //
        if(progressDialog == null){
            progressDialog = new ProgressDialog(SplashActivity.this);
            progressDialog.setMax((int)total);
            progressDialog.setTitle("下载中...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.show();

        }

        progressDialog.setProgress((int)current);
    }
}
